package aa.jx.register.controller;

import aa.jx.register.model.User;
import aa.jx.register.service.UserService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/send-verification-code")
    public Map<String, Object> sendVerificationCode(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        return userService.sendVerificationCode(email);
    }

    @PostMapping("/verify-email")
    public Map<String, Object> verifyEmail(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String code = request.get("code");
        return userService.verifyEmail(email, code);
    }

    @PostMapping("/complete-registration")
    public Map<String, Object> completeRegistration(@RequestBody Map<String, Object> request) {
        try {
            String token = (String) request.get("token");
            User user = new ObjectMapper().convertValue(request.get("user"), User.class);
            return userService.completeRegistration(token, user);
        } catch (Exception e) {
            e.printStackTrace(); // 打印错误堆栈
            return Map.of("success", false, "message", "服务器内部错误: " + e.getMessage());
        }
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, Object> request) {
        String email = (String) request.get("email");  // 改为 email
        String password = (String) request.get("password");
        Integer role = (Integer) request.get("role");
        return userService.login(email, password, role);  // 传递 email
    }

    @GetMapping("/info/{userId}")
    public Map<String, Object> getUserInfo(@PathVariable Integer userId) {
        return userService.getUserInfo(userId);
    }

    @PutMapping("/update")
    public Map<String, Object> updateUserInfo(@RequestBody User user,
                                              @RequestHeader("Authorization") String token) {
        try {
            // 从token中解析用户ID
            Integer userId = parseUserIdFromToken(token.replace("Bearer ", ""));
            user.setId(userId);

            return userService.updateUserInfo(user);
        } catch (Exception e) {
            return Map.of("success", false, "message", "更新失败: " + e.getMessage());
        }
    }

    @PostMapping("/adlogin")
    public Map<String, Object> adlogin(@RequestBody Map<String, Object> request) {
        String phone = (String) request.get("phone");  // 改为phone
        String password = (String) request.get("password");
        Integer role = (Integer) request.get("role");
        return userService.adlogin(phone, password, role);
    }


    @PostMapping("/update-password")
    public Map<String, Object> updatePassword(@RequestBody Map<String, String> request,
                                              @RequestHeader("Authorization") String token) {
        try {
            // 从token中解析用户ID (需要实现解析JWT的方法)
            Integer userId = parseUserIdFromToken(token.replace("Bearer ", ""));

            String oldPassword = request.get("oldPassword");
            String newPassword = request.get("newPassword");

            return userService.updatePassword(userId, oldPassword, newPassword);
        } catch (Exception e) {
            return Map.of("success", false, "message", "请求处理错误: " + e.getMessage());
        }
    }

    @PostMapping("/update-payword")
    public Map<String, Object> updatePayword(@RequestBody Map<String, String> request,
                                             @RequestHeader("Authorization") String token) {
        try {
            // 从token中解析用户ID
            Integer userId = parseUserIdFromToken(token.replace("Bearer ", ""));

            String oldPayword = request.get("oldPayword");
            String newPayword = request.get("newPayword");

            return userService.updatePayword(userId, oldPayword, newPayword);
        } catch (Exception e) {
            return Map.of("success", false, "message", "请求处理错误: " + e.getMessage());
        }
    }

    // 从JWT token解析用户ID的辅助方法
    private Integer parseUserIdFromToken(String token) {
        try {
            // 1. 验证token格式
            if (token == null || token.isEmpty()) {
                throw new IllegalArgumentException("Token不能为空");
            }

            // 2. 分割token为三部分
            String[] parts = token.split("\\.");
            if (parts.length != 3) {
                throw new IllegalArgumentException("无效的token格式");
            }

            // 3. 解码payload部分
            String payloadJson;
            try {
                // 注意：这里使用Base64.getDecoder()而不是UrlDecoder，因为generateJwtToken使用的是普通Base64编码
                payloadJson = new String(Base64.getDecoder().decode(parts[1]));
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("无效的token编码", e);
            }

            // 4. 解析payload JSON
            ObjectMapper mapper = new ObjectMapper();
            JsonNode payloadNode = mapper.readTree(payloadJson);

            // 5. 验证必要字段
            if (!payloadNode.has("sub")) {
                throw new IllegalArgumentException("token缺少用户ID(sub)字段");
            }

            // 6. 返回用户ID
            return payloadNode.get("sub").asInt();

        } catch (Exception e) {
            // 记录错误日志
            System.err.println("解析token失败: " + e.getMessage());
            throw new RuntimeException("解析token失败: " + e.getMessage(), e);
        }
    }
}